import VPlay 2.0
import QtQuick 2.0
import "../common"

import QuickUdpSocket 1.0

SceneBase {
  id: selectLevelScene

  // signal indicating that a level has been selected
  signal levelPressed(string selectedLevel)
  signal robotPressed(string selectedLevel, string ip)
  signal robotDisconnect(string disconnect_ip)

  property var robotList:[]
  property int timeout: 3000

  // background
  Rectangle {
    anchors.fill: parent.gameWindowAnchorItem
    color: "#47688e"
  }

  // back button to leave scene
  MenuButton {
    text: "返回"
    // anchor the button to the gameWindowAnchorItem to be on the edge of the screen on any device
    anchors.right: selectLevelScene.gameWindowAnchorItem.right
    anchors.rightMargin: 10
    anchors.top: selectLevelScene.gameWindowAnchorItem.top
    anchors.topMargin: 10
    onClicked: backButtonPressed()
  }

  Text {
    id: tipText
    anchors.horizontalCenter: parent.horizontalCenter
    y: 30
    font.pixelSize: 30
    color: "#fe95e9"
    visible: robotList.length <= 0
    text: "无连接，请打开机器人"
  }

  // levels to be selected
  Grid {
    anchors.centerIn: parent
    spacing: 10
    columns: 5

    add: Transition {
        NumberAnimation { properties: "x,y"; easing.type: Easing.OutBounce }
    }

    Repeater {
      id: repeater
      model: robotList
      MenuButton {
        text: modelData.number
        width: 50
        height: 50
        onClicked: {
          robotPressed("Controller.qml", modelData.ip)
        }
      }
    }
  }
  UdpSocket {
    id: udpreceive
    onMessageReceive: {

      var number = parseInt(msg.toString())
      function isBigEnough(element) {
        return element.number === number
      }

      var d = new Date()
      var t = d.getTime()
      var find = robotList.some(isBigEnough);
      if (!find) {
        //console.log(number)
        robotList.push({number: number, ip: sender_ip.slice(7), time: t})
        repeater.model = robotList;
      } else {
        robotList.forEach(function(element) {
          if (element.number === number)
            element.time = t
        });
      }

      return
    }
  }

  Timer {
    repeat: true
    running: true
    onTriggered: {
      robotList.forEach(function(element, index, array) {
        var d = new Date()
        var t = d.getTime()
        if (t - element.time > timeout) {//timeout秒没有心跳，删除该元素
          robotDisconnect(element.ip)
          array.splice(index, 1)
          repeater.model = array

          //console.log("Timer robotDisconnect")
        }
      })
      //if (robotList.length > 0)
      tipText.visible = robotList.length > 0 ? false : true
      //repeater.model = robotList;
    }
  }

  Component.onCompleted: {
    var result = udpreceive.socketBind(45455);
    //console.log("udpreceive.socketBind(45455) = ", result)
  }
}
